package mhuu.service;

import java.io.UnsupportedEncodingException;

import mhuu.view.ButtonPanel;
import mhuu.view.HttpRequestPanel;
import mhuu.view.HttpResponsePanel;
import mhuu.view.MainWindow;

public class SendHttpService {
	public static void sendHttp() {
		String address=ButtonPanel.jTextField.getText(); 
		String requestString=HttpRequestPanel.jTextArea.getText();
		address=address.replaceAll("http://", "");
		address=address.replaceAll("https://", ""); 
		if (address.contains("/")) {
			int index=address.indexOf("/");
			address=address.substring(0,index);   
		}
		if (address==null||"".equals(address.trim())) {
			HttpResponsePanel.jTextArea.setText("请输入正确的请求地址。。。");
			MainWindow.mainPanel.setVisible(true);
			return;
		}
		String result="";
		try {
		String host=address;
		int port=80;
		if (address.contains(":")) {
			String[] addarray=address.split(":");
			host=addarray[0];
			port=Integer.valueOf(addarray[1]);
		} 
			String requstHeadHost=host;
			if (port!=80&&port!=443) {
				requstHeadHost+=":"+port;
			}
		
			String content=HttpProtocolTxtService.getOkRequestContent(requestString,ButtonPanel.jTextField.getText(),requstHeadHost);
			HttpRequestPanel.jTextArea.setText(content);
			result=SocketService.sendBytesToHostPort(host, port, content.getBytes("utf-8"));
		} catch (Exception e) { 
			e.printStackTrace();
			result="出错了：\n";
			result=result+e.getMessage()+"\n";
		}
		HttpResponsePanel.jTextArea.setText(result);
		MainWindow.mainPanel.setVisible(true);
		
	} 
}
